<template>
  <div class="bgOrderSelectVehiclesMainFromFile h100">
    <a-row :gutter="[20, 8]">
      <a-col
        :xs="24"
        :sm="24"
        :md="24"
        :lg="8"
        :xl="6"
        :xxl="7">
        <!-- 车型，必填写 -->
        <car-model-select
          ref="carModelSelectRef"
          mode="default"
          :query="{ time: drawerOpenTime }"
          :has-all="false"
          :default-value="formData.modelId2"
          @changeoption="changeModelBefore"
          style="width: 100%"
        ></car-model-select>
      </a-col>
      <a-col
        :xs="24"
        :sm="24"
        :md="24"
        :lg="12"
        :xl="15"
        :xxl="15">
        <div class="withUploadArrowInputBox">
          <a-input :placeholder="$t('bgOrderFormFileUploadTip')" readonly :value="formData.fileName">
            <template slot="suffix">
              <a-upload
                :disabled="!formData.modelId2"
                :file-list="[]"
                :before-upload="beforeUpload"
                :customRequest="doUpload"
              >
                <a-icon type="upload" />
              </a-upload>
            </template>
          </a-input>
        </div>
      </a-col>
      <a-col
        :xs="24"
        :sm="24"
        :md="24"
        :lg="4"
        :xl="3"
        :xxl="2">
        <a-button @click="downloadFile" :loading="downloading">{{ $t('downloadTemplate') }}</a-button>
      </a-col>
    </a-row>
    <!-- 上传结果 -->
    <div class="uploadResult">
      <div>
        <span>{{ $t('fileVehicleNumber') }}：</span>
        <span>{{
          uploadResult ? uploadResult.totalNumber : '-'
        }}</span>
      </div>
      <div>
        <span>{{ $t('importVehicleNumber') }}：</span>
        <span>{{ uploadResult ? uploadResult.successNumber : '-' }}</span>
      </div>
      <div>
        <span>{{ $t('failVehicleNumber') }}：</span>
        <span>{{ uploadResult ? uploadResult.failNumber : '-' }}</span>
        <a
          v-if="uploadResult&&uploadResult.totalNumber"
          @click="exportFail"
          style="margin-left: 32px"
        >{{ $t('export') }}</a>
      </div>
    </div>
    <div v-if="uploadResult&&uploadResult.totalNumber" style="flex: 1 0 0;">
      <fail-list-from-file :pretreatmentId="formData.pretreatmentId"></fail-list-from-file>
    </div>
  </div>
</template>
<script>
import { mapState, mapGetters } from 'vuex'
import { downloadBlobFile } from '@/utils/functions'
import orderManagementApi from '@/api/modules/system/orderManagement'
import CarModelSelect from '@/views/components/CarModelSelect'
import FailListFromFile from './FailListFromFile.vue'
export default {
  components: {
    CarModelSelect,
    FailListFromFile
  },
  computed: {
    ...mapGetters(['drawerOpenTime']),
    ...mapState({
      formData: (state) => state.orderManagement.bgOrderFormData
    }),
    uploadResult () {
      return this.formData.uploadResult
    }
  },
  data () {
    return {
      downloading: false,
      uploading: true,
      exportLoadding: false
    }
  },
  methods: {
    // 选择车型
    changeModelBefore (val) {
      this.formData.modelId2 = val
      this.formData.fileName = ''
      this.formData.uploadResult = null
    },
    // 检测文件
    beforeUpload (file) {
      const reg = /^.*\.(?:xls|xlsx)$/i // 文件名可以带空格
      if (!reg.test(file.name)) {
        this.$message.error(this.$t('pleaseSelect') + this.$t('formatFiles').toLowerCase())
        return false
      }
      this.formData.fileName = file.name
      this.formData.uploadResult = null
      return true
    },
    doUpload (options) {
      this.uploading = true
      this.formData.pretreatmentId = ''
      const formData = new FormData()
      formData.append('file', options.file)
      orderManagementApi
        .uploadBgServiceOrderFile(formData, { modelId: this.formData.modelId2 })
        .then((res) => {
          this.formData.pretreatmentId = res.data.pretreatmentId
          this.formData.uploadResult = res.data
          this.$message.success(this.$t('uploadedSuccessfully'))
        })
        .finally(() => {
          this.uploading = false
        })
        .catch(() => {
          this.formData.fileName = ''
        })
    },
    // 下载模板
    downloadFile () {
      this.downloading = true
      this.$api
        .downloadTaskCarTpl()
        .then((res) => {
          downloadBlobFile(res, `${this.$t('downloadTemplate')}.xlsx`)
        })
        .finally(() => {
          this.downloading = false
        })
    },
    // 获取选择车辆数量、车型Id、车型代码、车型名称、版型
    getFormData () {
      const result = {
        total: 0,
        modelId: this.formData.modelId2,
        modelCode: '',
        trimLevel: '',
        modelName: ''
      }
      if (this.uploadResult) {
        result.total = this.uploadResult.successNumber
      }
      const obj = this.$refs.carModelSelectRef.modelOptions.find((item) => item.id === this.formData.modelId2)
      if (obj) {
        result.modelCode = obj.code
        result.trimLevel = obj.trimLevel
        result.modelName = obj.title
      }
      return result
    },
    exportFail () {
      this.exportLoadding = true
      orderManagementApi.uploadBgServiceOrderFileFailExport({ pretreatmentId: this.formData.pretreatmentId })
        .then((res) => {
          downloadBlobFile(res, `${this.$t('exceptionInformation')}.xlsx`)
        })
        .finally(() => {
          this.exportLoadding = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
.bgOrderSelectVehiclesMainFromFile {
  display: flex;
  flex-direction: column;
  .uploadResult {
    display: flex;
    width: 100%;
    margin-top: 16px;
    > div {
      margin-right: 20px;
      min-width: 200px;
    }
  }
}
</style>
